import React, {FC, useEffect, useState} from "react";
import {AutoComplete, Checkbox, Empty, Form, message, Popconfirm, Space, Tree, TreeDataNode, TreeProps} from "antd";
import {add, getFilterOne, update} from "@/pages/filter/service";
import {BetaSchemaForm} from "@ant-design/pro-components";
import {useRequest} from "@@/exports";
import {getFormOne} from "@/pages/dynamic-form/design-form/service";
import {ArrowDownOutlined, ArrowUpOutlined, DeleteOutlined, EditOutlined, PlusOutlined} from "@ant-design/icons";
import {getSettingList} from "@/pages/public-setting/service";

const updateCheckedStatus = (ret: any[], checkedKeys: any[] = []) => {
  ret.forEach((item: any) => {
    if (checkedKeys.includes(item.key)) {
      item.isShow = true
    } else {
      item.isShow = false
    }
    if (item.children) {
      updateCheckedStatus(item.children, checkedKeys)
    }
  })
}

interface CustomLeafTreeDataProps {
  cascaderVal: any[]
  treeData: any[]
  setTreeData: any
  onLoading?: any
}

const CustomLeafTreeData: FC<CustomLeafTreeDataProps> = ({
                                                           cascaderVal = [],
                                                           treeData = [],
                                                           setTreeData,
                                                           onLoading,
                                                         }) => {
  const [addForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);

  const initalCheckedKeys = (ret: any[], checkedKeys: any[] = []) => {

    ret.forEach((item: any) => {
      if (item.isShow) {
        checkedKeys.push(item?.key || item?.value)
      }
      if (item.children) {
        initalCheckedKeys(item.children, checkedKeys)
      }
    })

    return checkedKeys
  }

  // 筛选条件
  const {loading, refresh: loadTreeData} = useRequest(async () => {
    let res = await getFilterOne({
      categoryId: cascaderVal[cascaderVal?.length - 1],
    });

    // console.log('res', res);

    if (!res?.data) {
      res = await getFormOne({
        type: cascaderVal[cascaderVal?.length - 1],
      });
      // console.log('res2', res);
      if (!res?.data) {
        setTreeData([])
        return
      }
      const ret = res?.data?.formHeaderList?.map((item: any) => ({
        ...item,
        title: item.property,
        value: item.id,
        label: item.property,
        key: item.id,
        // children: [{ label: 'aaa', value: 0 }]
      }))

      setTreeData(ret)
    } else {
      const value = res?.data?.value
      let ret = []
      try {
        ret = JSON.parse(value)
        // console.log('ret', ret)
        setTreeData(ret)
        const keys = initalCheckedKeys(ret)
        // eslint-disable-next-line @typescript-eslint/no-use-before-define
        setCheckedKeys(keys)
      } catch (e) {
      }
    }
    return res;
  }, {
    refreshDeps: [cascaderVal],
  });

  useEffect(() => {
    onLoading?.(loading)
  }, [loading])

  const onExpand: TreeProps['onExpand'] = (expandedKeysValue) => {
    // console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };

  const sortTreeData = (data: any[]) => {
    for (let i = 0; i < data.length; i++) {
      data[i].sort = i;
      if (data[i].children) {
        sortTreeData(data[i].children!);
      }
    }
  }

  const handleSave = async (record: any = null, values: any = null) => {
    const hide = message.loading('正在保存');

    try {
      if (record && values) {
        if (Array.isArray(record.children)) {
          record.children.push({
            ...values,
            label: values.filterValue,
            title: values.filterValue,
            value: values.field,
            key: values.field,
          })
        } else {
          record.children = [
            {
              ...values,
              label: values.filterValue,
              title: values.filterValue,
              value: values.field,
              key: values.field,
            }
          ]
        }
      }

      // console.log('rightOps', rightOps);

      const {data: filterOne} = await getFilterOne({
        categoryId: cascaderVal[cascaderVal?.length - 1],
      })
      // console.log(filterOne);
      sortTreeData(treeData)
      if (filterOne?.id) {
        await update({
          id: filterOne.id,
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(treeData)
        })
      } else {
        await add({
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(treeData)
        })
      }

      setTreeData([...treeData])

      hide();
      loadTreeData()
      message.success('保存成功');
      return true
    } catch (e) {
      hide();
      message.error('保存失败请重试！');
      return false;
    }
  }

  const delChild = (data: any[], field: any) => {
    data.forEach((item, index) => {
      if (item.field === field) {
        data.splice(index, 1)
      }
      if (item.children) {
        delChild(item.children, field)
      }
    })
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const handleDel = async (record: any = null, values: any = null) => {
    const hide = message.loading('正在删除');

    try {
      const {data: filterOne} = await getFilterOne({
        categoryId: cascaderVal[cascaderVal?.length - 1],
      })
      // console.log(filterOne);
      let newRightOps = [...treeData]
      delChild(newRightOps, record?.field)
      // console.log('newRightOps', newRightOps);

      if (filterOne?.id) {
        await update({
          id: filterOne.id,
          categoryId: cascaderVal[cascaderVal?.length - 1],
          name: `${cascaderVal[cascaderVal?.length - 1]}-分类-筛选条件`,
          value: JSON.stringify(treeData)
        })
      } else {
        return false
      }

      setTreeData([...treeData])

      hide();
      message.success('删除成功');
      return true
    } catch (e) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  }

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const onCheck: TreeProps['onCheck'] = (checkedKeysValue, info) => {
    // console.log('onCheck', checkedKeysValue, info, rightOps);
    // info.checkedNodes.forEach((item: any) => {
    //   item.isShow = true
    // })
    // setRightOps([...rightOps])
    setCheckedKeys(checkedKeysValue as React.Key[]);
    updateCheckedStatus(treeData, checkedKeysValue as React.Key[])
    setTreeData([...treeData])
    handleSave()
  };

  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const onSelect: TreeProps['onSelect'] = (selectedKeysValue, info) => {
    // console.log('onSelect', info);
    setSelectedKeys(selectedKeysValue);
  };

  const loop = (
    data: any[],
    key: React.Key,
    callback: (node: TreeDataNode, i: number, data: TreeDataNode[]) => void,
  ) => {
    for (let i = 0; i < data.length; i++) {
      data[i].sort = i;
      if (data[i].key === key) {
        return callback(data[i], i, data);
      }
      if (data[i].children) {
        loop(data[i].children!, key, callback);
      }
    }
  };

  const [options, setOptions] = useState<any[]>([])
  const {data: settingInfo} = useRequest(async () => {
    const res = await getSettingList()
    const newVal: any = {}
    Object.keys(res?.data).forEach((key) => {
      try {
        newVal[key] = JSON.parse(res?.data[key]?.value || '')
      } catch (e) {
      }
    })
    newVal.publicFilteringCriteria = newVal?.publicFilteringCriteria?.map((item: any) => ({
      ...item,
      label: `${item.name}(${item.fieldName})`,
      value: item.fieldName
    })) || []

    return {
      data: newVal
    }
  }, {
    onSuccess(data) {
      setOptions(data?.publicFilteringCriteria)
    },
  });

  return <>
    {treeData?.length > 0 ? <>
      <Checkbox
        checked={treeData?.every((item: any) => item.isShow)}
        style={{marginLeft: 24, marginBottom: 5}}
        onChange={async (e) => {
          // console.log(`checked = ${e.target.isShow}`);
          if (e.target.checked) {
            const checkedKeysValue = treeData?.map((item: any) => item.id)
            setCheckedKeys(checkedKeysValue)
            updateCheckedStatus(treeData, checkedKeysValue as React.Key[])
            setTreeData([...treeData])
            await handleSave()
          } else {
            setCheckedKeys([])
            updateCheckedStatus(treeData, [] as React.Key[])
            setTreeData([...treeData])
            await handleSave()
          }
        }}>
        <span style={{paddingLeft: 4}}>全选/取消全选</span>
      </Checkbox>
      <Tree
        style={{background: 'rgba(223, 223, 223,.17)'}}
        checkable
        onExpand={onExpand}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        onSelect={onSelect}
        selectedKeys={selectedKeys}
        treeData={treeData}
        titleRender={(record: any) => {
          return <Space size={12}>
            <span>{record?.title || '-'}{cascaderVal?.length === 1 && record?.fieldName  ? `(${record?.fieldName})` : ''} </span>


            <a onClick={() => {
              loop(treeData, record?.key, (current, currentIndex, arr) => {
                if (currentIndex <= 0) {
                  return
                }
                // console.log('current', current, currentIndex)
                const tem = {...arr?.[currentIndex - 1]}
                arr[currentIndex - 1] = current
                arr[currentIndex] = tem
                setTreeData([...treeData])
                handleSave()
              })
            }}><ArrowUpOutlined/></a>
            <a onClick={() => {
              loop(treeData, record?.key, (current, currentIndex, arr) => {
                if (currentIndex >= arr?.length - 1) {
                  return
                }
                // console.log('current', current, currentIndex)
                const tem = {...arr?.[currentIndex + 1]}
                arr[currentIndex + 1] = current
                arr[currentIndex] = tem
                setTreeData([...treeData])
                handleSave()
              })
            }}><ArrowDownOutlined/></a>
            {/*外层有id*/}
            {record?.id ? <Space size={12}>
              <BetaSchemaForm<any>
                layoutType={'ModalForm'}
                onFinish={async (values) => {
                  return handleSave(record, values);
                }}
                form={addForm}
                modalProps={{
                  destroyOnClose: true,
                  title: "增加筛选条件",
                  width: "500px",
                }}
                trigger={<a onClick={() => {
                  // setCurrentData(record)
                  // console.log('record', record);

                  addForm.setFieldsValue({
                    parentField: record?.name + '',
                  })
                }}>
                  <PlusOutlined/>
                </a>}
                columns={[
                  {
                    title: '筛选值',
                    dataIndex: 'filterValue',
                    valueType: 'text',
                    formItemProps: () => {
                      return {
                        rules: [{required: true, message: '此项为必填项'}],
                      };
                    },
                  },
                  {
                    title: '父级',
                    dataIndex: 'parentField',
                    valueType: 'select',
                    fieldProps: {
                      disabled: true
                    },
                    // eslint-disable-next-line @typescript-eslint/no-unused-vars
                    valueEnum(row) {
                      // console.log(rightOps);
                      const map: any = {}
                      treeData.forEach((item: any) => {
                        map[item.name] = {
                          text: item.property,
                          status: item.name
                        }
                      })
                      // console.log('map', map);

                      return map
                    },
                    formItemProps: () => {
                      return {
                        rules: [{required: true, message: '此项为必填项'}],
                      };
                    },
                  },
                  {
                    title: '筛选标识',
                    dataIndex: 'field',
                    valueType: 'text',
                    fieldProps: {
                      disabled: true,
                    },
                    initialValue: new Date().getTime().toString(36) + Math.random().toString(36).substr(2, 9),
                    formItemProps: () => {
                      return {
                        rules: [{required: true, message: '此项为必填项'}],
                      };
                    },
                  },
                  {
                    title: '显示此筛选',
                    dataIndex: 'checked',
                    valueType: 'switch',
                    initialValue: true,
                    formItemProps: () => {
                      return {
                        rules: [{required: true, message: '此项为必填项'}],
                      };
                    },
                  },
                ]}
              />
              {/*编辑筛选条件 只有一级分类，同时作为该分类公共筛选条件使用*/}
              {cascaderVal?.length === 1 && <BetaSchemaForm<any>
                layoutType={'ModalForm'}
                onFinish={async (values) => {
                  // console.log('values', values, record, cascaderVal)
                  loop(treeData, record.key, (item) => {
                    Object.keys(values).forEach(key => {
                      item[key] = values[key]
                    })
                  })
                  return handleSave();
                }}
                form={editForm}
                modalProps={{
                  destroyOnClose: true,
                  title: "编辑筛选条件",
                  width: "500px",
                }}
                trigger={
                  <a
                    type={'link'}
                    onClick={() => {
                      // setCurrentData(record)
                      // console.log('record', record);
                      editForm.resetFields()
                      editForm.setFieldsValue({...record})
                    }}
                  ><EditOutlined/></a>
                }
                columns={[
                  {
                    title: '排序',
                    dataIndex: 'sort',
                    valueType: 'digit',
                    initialValue: addForm.getFieldsValue()?.home_grid?.length + 1 || 0,
                    width: 120,
                  },
                  {
                    title: '名称',
                    dataIndex: 'title',
                  },
                  {
                    title: '字段名',
                    dataIndex: 'fieldName',
                    renderFormItem() {
                      return <AutoComplete
                        options={options}
                        // style={{ width: 200 }}
                        // onSelect={onSelect}
                        onSearch={(text) => {
                          const newOptions = settingInfo?.publicFilteringCriteria.filter((item: any) => item.value?.indexOf(text) !== -1)
                          setOptions(newOptions)
                        }}
                        placeholder="请输入字段名"
                      />
                    }
                  },
                  {
                    title: '筛选类型',
                    dataIndex: 'filterType',
                    valueType: 'select',
                    valueEnum: {
                      range: {text: '范围筛选'},
                      value: {text: '值筛选'}
                    }
                  },
                  {
                    title: '是否显示',
                    dataIndex: 'isShow',
                    valueType: 'switch',
                    initialValue: true,
                    fieldProps: {
                      unCheckedChildren: '隐藏',
                      checkedChildren: '显示'
                    },
                    // width: '40%',
                  },
                ]}
              />}
            </Space> : <Space size={12}>
              <Popconfirm
                title="删除列"
                description={<>
                  <p>确认删除 <b>{record?.name}</b> 筛选项?</p>
                </>}
                onConfirm={async () => {
                  const isOk = handleDel(record)
                  return isOk;
                }}
                okText="是"
                cancelText="否"
              >
                <a> <DeleteOutlined/></a>
              </Popconfirm>
            </Space>}
          </Space>
        }}
      />
    </> : (!loading ? <Empty style={{margin: 'auto'}}/> : <></>)}
  </>
}

export default CustomLeafTreeData
